package com.yequan.leetcode.tree.treebfs;

import com.yequan.leetcode.tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author : Administrator
 * @date : 2020/4/4
 */
public class TreeBfs {

    /**
     * 使用队列实现广度优先
     *
     * @param root
     * @return
     */
    public List<Integer> bfs1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            res.add(node.val);
            if (null != node.left) {
                queue.offer(node.left);
            }
            if (null != node.right) {
                queue.offer(node.right);
            }
        }
        return res;
    }

    public void bfs2(TreeNode node, int level, List<List<Integer>> res) {
        if (null != node) {
            if (level == res.size()) {
                res.add(new ArrayList<>());
            }
            res.get(level).add(node.val);
            if (null != node.left) {
                bfs2(node.left, level + 1, res);
            }
            if (null != node.right) {
                bfs2(node.right, level + 1, res);
            }
        }
    }

}
